#include "crc16.h"

void crc16_init(crc16_data_t *crc16Config)
{
    // initialize running crc and byte count
    crc16Config->currentCrc = 0;
}

void crc16_update(crc16_data_t *crc16Config, const uint8_t *src, uint32_t lengthInBytes)
{
	uint32_t crc = crc16Config->currentCrc;

	uint32_t i;
	uint32_t j;
	uint32_t Byte;
	uint32_t temp;

	for (j = 0; j<lengthInBytes; ++j)
	{		
		Byte = src[j];

		crc ^= Byte << 8;

		for (i = 0; i< 8; ++i)
		{
			temp = crc << 1;

			if ((crc & 0x8000) == 0x8000)
			{
				temp ^= 0x1021;
			}

			crc = temp;
		}
	}

	crc16Config->currentCrc = crc;
}

void crc16_finalize(crc16_data_t *crc16Config, uint16_t *hash)
{
    *hash = crc16Config->currentCrc;
}
